package com.app.controller.backstage;

import com.app.common.Result;
import com.app.model.AdminUserModel;
import com.app.model.AreaModel;
import com.app.model.CategoryModel;
import com.app.service.AdminUserService;
import com.app.service.AreaService;
import com.app.util.CommonHelp;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

@Controller
@RestController
@RequestMapping("/admin/area")
public class AreaAdminController {
    @Autowired
    private AreaService areaService;
    @Autowired
    private AdminUserService adminUserService;

    //查所有县市
    @GetMapping("/selectCity")
    public Result<Object> selectCity() {
        return Result.success(areaService.selectCity());
    }

    //乡镇
    @GetMapping("/selectTown")
    public Result<Object> selectTown(Integer id) {
        return Result.success(areaService.selectTown(id));
    }

    //村
    @GetMapping("/selectVillage")
    public Result<Object> selectVillage(Integer id) {
        return Result.success(areaService.selectVillage(id));
    }

    @GetMapping("/selectVillageByLevel")
    public Result<Object> selectVillageByLevel() {
        return Result.success(areaService.selectVillageByLevel());
    }

    //三级
    @GetMapping("/selectTree")
    public Result<Object> selectTree() {
        List<AreaModel> areaModels = areaService.selectTree();//全查
        if (areaModels == null) {
            return Result.error(500, "暂无数据");
        }
        List<Integer> arr1 = new ArrayList<>();
        for (int i = 0; i < areaModels.size(); i++) {
            arr1.add(areaModels.get(i).getId());
        }
        Integer ArrId = 1;
        boolean result1 = arr1.contains(ArrId);
        List<Integer> pidArr1 = new ArrayList<>();
        if (!result1) {
            for (int i = 0; i < areaModels.size(); i++) {

                boolean PidResult = arr1.contains(areaModels.get(i).getPid());
                if (!PidResult) {
                    pidArr1.add(areaModels.get(i).getPid());
                }
            }
            pidArr1.add(ArrId);
            arr1.addAll(pidArr1);
            LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(arr1);
            ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
            List<AreaModel> permissionModels1 = new ArrayList<>();
            for (int i = 0; i < listWithoutDuplicates.size(); i++) {
                AreaModel areaModel = areaService.selectById(listWithoutDuplicates.get(i));
                permissionModels1.add(areaModel);
            }
            return Result.success(findChildren(permissionModels1, 0));
        }
        return Result.success(findChildren(areaModels, 0));
    }

    private List<AreaModel> findChildren(List<AreaModel> modelList, Integer pid) {
        List<AreaModel> personModelList = new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if (modelList.get(i).getPid().equals(pid)) {
                AreaModel model = modelList.get(i);
                List<AreaModel> modelList1 = findChildren(modelList, model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    model.setChildren(modelList1);
                }
                personModelList.add(model);
            }
        }
        return personModelList;
    }

    @GetMapping("/deleteArea")
    public Result<Object> deleteCategory(Integer id) {
        AreaModel areaModel = areaService.selectById(id);
        if (areaModel.getPid() == 0) {
            return null;
        }
        AdminUserModel userByVillageId = adminUserService.getUserByVillageId(id);
        areaService.deleteCategory(id);
        adminUserService.deleteAdmin(userByVillageId.getId());
        return Result.success("删除成功");
    }

    @PostMapping("/editArea")
    public Result<Object> getDepList(
            @RequestBody AreaModel model,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (model.getId() != null && model.getId() > 0) {
            model.setUpdateTime(CommonHelp.getNowTimestamp());
            areaService.update(model);
        } else {
            model.setCreateTime(CommonHelp.getNowTimestamp());
            areaService.insert(model);
            if (model.getLevel() == 3) {
                String salt = "qh_";
                String pwd1 = md5Hex("jfsc_admin" + salt);
                AdminUserModel adminUserModel = new AdminUserModel();
                adminUserModel.setVillageId(model.getId());
                adminUserModel.setRoles(12);
                adminUserModel.setRealName(model.getName());
                adminUserModel.setUsername(model.getName());
                adminUserModel.setPassword(pwd1);
                adminUserService.insertAdmin(adminUserModel);
            }
        }
        return Result.success("操作成功");
    }

    @GetMapping("/areaStatus")
    public Result<Object> categoryStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AreaModel model = areaService.getAreaById(id);
        model.setStatus(status);
        areaService.update(model);
        return Result.success("操作成功");
    }
}
